package com.akcome.apollo.config;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权限访问时触发
 * @author wn
 *
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        
  	  boolean isAjax = "XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"));
  	  if(isAjax){
  		  //返回json形式的错误信息
  		  httpServletResponse.setCharacterEncoding("UTF-8");
  		  httpServletResponse.setContentType("application/json");
  		  httpServletResponse.getWriter().println("{\"code\":403,\"message\":\"权限不足\",\"data\":\"\"}");
  		  httpServletResponse.getWriter().flush();
  	  }else{
  		  httpServletResponse.sendRedirect("/login");
  	  }
  	  
    }
}
